<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="formDisabled">
      <!-- 主表单区域 -->
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">

        <a-row>
          <a-col :span="12">
            <a-form-model-item label="配方变更单号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="code">
              <a-input v-model="model.code" placeholder="" disabled></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="12" >
            <a-form-model-item label="配方编码" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="formulaId">
              <j-dict-select-tag type="list" v-model="model.formulaId" dictCode="ips_pg_formula_list,formula_code,id" placeholder="请选择配方编码" />
            </a-form-model-item>
          </a-col>
        </a-row>

        <a-row>
          <a-col :span="12">
            <a-form-model-item label="配方号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="formulaNumber">
              <a-input v-model="model.formulaNumber" placeholder="请输入配方号" :disabled="true" ></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="视比重" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="apparentProportion">
              <a-input v-model="model.apparentProportion" placeholder="请输入视比重" ></a-input>
            </a-form-model-item>
          </a-col>
        </a-row>

        <a-row>
          <a-col :span="12">
            <a-form-model-item label="配方要求" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="formulaDemand">
              <a-input v-model="model.formulaDemand" placeholder="请输入配方要求"  ></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="包装要求" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="packageDemand">
              <a-input v-model="model.packageDemand" placeholder="请输入包装要求"  ></a-input>
            </a-form-model-item>
          </a-col>
        </a-row>

        <a-input v-model="model.flowType" placeholder="" type="hidden" ></a-input>
        <!--<a-input v-model="model.formulaId" placeholder="" type="hidden" ></a-input>-->
        <a-input v-model="model.orderId" placeholder="" type="hidden" ></a-input>
        <a-input v-model="model.orderGoodsId" placeholder="" type="hidden" ></a-input>

        <a-row style="margin-top: 20px">
        </a-row>

        <a-row style="margin-left: -10px">
          <a-col :span="24">
            <j-vxe-table
              keep-source
              :ref="refKeys[1]"
              :loading="fileTable.loading"
              :columns="fileTable.columns"
              :dataSource="fileTable.dataSource"
              :maxHeight="300"
              :disabled="formDisabled"
              :rowNumber="true"
              :rowSelection="true"
              :toolbar="true"
            >
              <template v-slot:action="props">
                <a @click="handlePreviewFile(props)">预览</a>
              </template>
            </j-vxe-table>
          </a-col>
        </a-row>

      </a-form-model>
    </j-form-container>
    <!-- 子表单区域 -->
    <a-tabs v-model="activeKey" @change="handleChangeTabs">
      <a-tab-pane tab="配方清单" :key="refKeys[0]" :forceRender="true">
        <a-table
          :ref="refKeys[0]"
          :columns="formulaListTable.columns"
          :dataSource="formulaListTable.dataSource"
          :pagination="false"
          bordered
          size="middle"
          rowKey="id"
          style="width: 100%; min-width: 100%"
          :footer="formulaListFooter"
        >
        </a-table>
      </a-tab-pane>
    </a-tabs>
  </a-spin>
</template>

<script>
  import { getAction, httpAction, postAction } from '@/api/manage'
  import { FormTypes, getRefPromise, VALIDATE_NO_PASSED } from '@/utils/JEditableTableUtil'
  import { JVxeTableModelMixin } from '@/mixins/JVxeTableModelMixin'
  import { JVXETypes } from '@/components/jeecg/JVxeTable'
  import store from '@/store'
  import JSelectDepart from '@/components/jeecgbiz/JSelectDepart'
  import moment from 'dayjs'
  import ErpGoodsSupplier from '@/components/base/ErpGoodsSupplier'
  import GoodsSupplier from '@/components/base/GoodsSupplier'
  import { initDictOptions } from '@/components/dict/JDictSelectUtil'
  import TslSupplier from '@comp/tsl/TslSupplier.vue'
  import { parseTime } from '@/utils/index.js'
  import { definitionStartByDataId, isFirstInitiator } from '@views/flowable/api/definition'
  import TslSelectUserSingle from '@/components/tsl/TslSelectUserSingle.vue'
  import { FilePreview } from '@/utils/tslCommon'

  export default {
    name: 'IpsPgOrderFormulaModifyForm',
    mixins: [JVxeTableModelMixin],
    components: {
      // ErpGoodsListModel,
      // PlanModal,
      // ErpSupplier,
      JSelectDepart,
      ErpGoodsSupplier,
      GoodsSupplier,
      TslSupplier,
      TslSelectUserSingle,
    },
    data() {
      return {
        labelCol: {
          xs: { span: 24 },
          sm: { span: 6 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 },
        },
        dict: {
          unit: [{ label: '个', value: '1' }],
        },
        priceTypeOption: [
          {
            value: '到库价格',
            label: '到库价格',
          },
          {
            value: '出厂价格',
            label: '出厂价格',
          },
          {
            value: '到港价格',
            label: '到港价格',
          },
        ],
        model: {
          flowType: '1',
          code: '',
          orderId: '',
          orderGoodsId: '',
          ipsPgFormulaMaterialDetailList: [],
          formulaModifyFilesList: [],
        },
        supplier: {},
        supplyShow: true,
        // 新增时子表默认添加几行空数据
        addDefaultRowNum: 1,
        validatorRules: {
        },
        refKeys: ['bussOrderFormulaModifyDetail','fileTable'],
        tableKeys: ['bussOrderFormulaModifyDetail'],
        activeKey: 'bussOrderFormulaModifyDetail',
        // tsl配方通知单明细
        formulaListTable: {
          columns: [
            { title: '物料编码',
              dataIndex: 'materialCode',
              key: 'materialCode',
              align: "center",
              width: '16%'
            },
            { title: '物料名称',
              dataIndex: 'materialName',
              key: 'materialName',
              align: "center",
              width: '20%'
            },
            { title: '规格型号',
              dataIndex: 'materialSpec',
              key: 'materialSpec',
              align: "center",
              width: '15%'
            },
            { title: '单位',
              dataIndex: 'materialUnit_dictText',
              key: 'materialUnit_dictText',
              align: "center",
              width: '16%'
            },
            { title: '配方%',
              dataIndex: 'formulaProportion',
              key: 'formulaProportion',
              align: "center",
              width: '16%'
            },
            { title: '实际数量',
              dataIndex: 'actualNumber',
              key: 'actualNumber',
              align: "center",
              width: '16%'
            }
          ],
          dataSource: []
        },
        fileTable: {
          loading: false,
          dataSource: [],
          columns: [
            {
              title: '附件',
              key: 'filePath',
              type: JVXETypes.file,
              token: true,
              disabled:this.formDisabled,
              responseName: 'message',
              width: '200px',
              placeholder: '请选择文件',
              defaultValue: '',
            },
            {
              title: '附件说明',
              key: 'fileDesc',
              type: JVXETypes.input,
              width: '200px',
              placeholder: '请输入${title}',
              defaultValue: '',
            },
            {
              title: '操作',
              key: 'action',
              type: JVXETypes.slot,
              fixed: 'right',
              minWidth: '100px',
              align: 'center',
              slotName: 'action',
            },
          ],
        },
        url: {
          add: '/ipspgorderformulamodify/ipsPgOrderFormulaModify/add',
          edit: '/ipspgorderformulamodify/ipsPgOrderFormulaModify/edit',
          queryById: '/ipspgorderformulamodify/ipsPgOrderFormulaModify/queryById',
          pgFormulaMaterialDetails: {
            list: '/ipspgorderformulamodify/ipsPgOrderFormulaModify/queryPgFormulaMaterialDetailsByMainId',
          },
          queryFormulaDetails: '/ipspgformulalist/ipsPgFormulaList/queryFormulaDetails',
        },
        unitDictOptions: {},
        zlunitDictOptions: {},
      }
    },
    watch: {
      // 监听配方编码变化
      'model.formulaId': {
        immediate: true,
        handler(newVal) {
          if (newVal) {
            if (!this.model.id) {
              this.loadFormulaDetail(newVal)
            }
          }
        }
      }
    },
    props: {
      //表单禁用
      disabled: {
        type: Boolean,
        default: false,
        required: false,
      },
      customFormData: {
        type: Object,
        default: () => {
          return {}
        },
        required: false,
      },
    },
    computed: {
      totalFormulaProportion() {
        return this.formulaListTable.dataSource.reduce((sum, item) => {
          return sum + (parseFloat(item.formulaProportion) || 0);
        }, 0).toFixed(4);
      },
      totalActualNumber() {
        return this.formulaListTable.dataSource.reduce((sum, item) => {
          return sum + (parseFloat(item.actualNumber) || 0);
        }, 0).toFixed(4);
      },
      formDisabled() {
        return this.disabled
      },
    },
    created() {
      this.model.createTime = moment().format('YYYY-MM-DD HH:mm:ss')
      let user = store.getters.userInfo
      if (!this.model.createBy) {
        this.model.createBy = user.username
        this.model.createOrgcode = user.departIds
      }

      this.initDictConfig()

      //如果是审批流进来的时候要将审批流的数据显示出来
      if (this.customFormData.id != null) {
        this.model = this.customFormData
        //刷新子表数据
        this.editAfter()
      }

      if (!this.model.id) { // 仅新增时添加默认行
        this.fileTable.dataSource = [{}];
      }
    },
    mounted() {},
    methods: {
      getPfCode() {
        postAction('/sys/fillRule/executeRuleByCode/tsl_formula_modify_code', {}).then((res) => {
          this.model.code = res.result
        })
      },
      initDictConfig() {
        //初始化字典 - 主单位
        initDictOptions('ji_unit').then((res) => {
          let unitDictOptions = this.unitDictOptions
          if (res.success) {
            res.result.forEach(function (item, index) {
              unitDictOptions[item.value] = item.label
            })
          }
          this.unitDictOptions = unitDictOptions
        })
      },
      addTemporary() {
        //临时新增
        if (this.model.detaillist && this.model.detaillist.length > 0 && this.model.detaillist[0].planCode) {
          this.$XModal.message({ message: '临时不能与计划混加', status: 'warning' })
          return
        }
        this.$nextTick(() => {
          this.$refs.selectGoodsList.add()
        })
      },
      addPlan() {
        //追加选择采购计划
        this.$nextTick(() => {
          this.$refs.plan.add()
        })
      },
      addBefore() {
        this.fileTable.dataSource = []
      },
      add(ordrObj, materialObj) {
        this.getPfCode()
        console.log("订单ID：" + ordrObj.id)
        console.log("产品ID：" + materialObj.id)
        this.model.orderId = ordrObj.id;
        this.model.orderGoodsId = materialObj.id;
      },
      getAllTable() {
        let values = this.tableKeys.map((key) => getRefPromise(this, key))
        return Promise.all(values)
      },
      /** 调用完edit()方法之后会自动调用此方法 */
      editAfter(record) {
        //如果没有明细先要复制一个空数组
        if (!record || record.ipsPgFormulaMaterialDetailList == null) {
          this.model.ipsPgFormulaMaterialDetailList = []
        }

        if (this.model.id) {
          let params = { mainId: this.model.id }
          this.requestSubTableData(
            this.url.pgFormulaMaterialDetails.list,
            params,
            this.formulaListTable,
            this.fileTable
          )

          //刷新明细的时候 还要将这个数据传输到要提交的表单中
          if (this.formulaListTable) {
            this.model.ipsPgFormulaMaterialDetailList = this.formulaListTable.dataSource
          }

          if (this.fileTable) {
            this.model.formulaModifyFilesList = this.fileTable.dataSource
          }
        }

        this.$nextTick(() => {})
      },
      requestSubTableData(url, params, formulaListTable, fileTable) {
        getAction(url, params).then(res => {
          if (res.success) {
            formulaListTable.dataSource = res.result.pgFormulaMaterialDetailList.map(item => ({
              ...item,
            })),
          fileTable.dataSource = res.result.formulaModifyFilesList
          }
        })
      },
      //校验所有一对一子表表单
      validateSubForm(allValues) {
        return new Promise((resolve, reject) => {
          Promise.all([])
            .then(() => {
              resolve(allValues)
            })
            .catch((e) => {
              if (e.error === VALIDATE_NO_PASSED) {
                // 如果有未通过表单验证的子表，就自动跳转到它所在的tab
                this.activeKey = e.index == null ? this.activeKey : this.refKeys[e.index]
              } else {
                validateError(e)
              }
            })
        })
      },
      /** 整理成formData */
      classifyIntoFormData(allValues) {
        let main = Object.assign(this.model, allValues.formValue)
        return {
          ...main, // 展开
          bussMaterialProcurementDetailList: allValues.tablesValue[0].values,
        }
      },
      validateError(msg) {
        this.$message.error(msg)
      },
      submitForm() {
        const that = this
        // 触发表单验证
        // this.$refs.bussOrderFormulaModifyDetail.validateTable().then((errMap) => {
        //   if (errMap) {
        //     this.$message.error('请检查表单明细内容')
        //     return
        //   } else {
        //
        //   }
        // })
        this.$refs.form.validate((valid) => {
          if (valid) {
            that.confirmLoading = true
            let httpurl = ''
            let method = ''
            if (!this.model.id) {
              httpurl += this.url.add
              method = 'post'
            } else {
              httpurl += this.url.edit
              method = 'put'
            }

            // if (this.ipsTslFormulaNoticeDetailTable && this.ipsTslFormulaNoticeDetailTable.dataSource) {
            //   this.model.ipsPgFormulaMaterialDetailList = this.$refs.bussOrderFormulaModifyDetail.getTableData()
            //   this.model.ipsPgFormulaMaterialDetailList.forEach((element) => {
            //     element.id = null
            //   })
            // }
            //
            // if (!this.model.ipsPgFormulaMaterialDetailList || this.model.ipsPgFormulaMaterialDetailList.length <= 0) {
            //   this.$message.warning('没有选择任何物料不能保存')
            //   that.confirmLoading = false
            //   return
            // }

            if (this.fileTable && this.fileTable.dataSource) {
              this.model.formulaModifyFilesList = this.$refs.fileTable.getTableData()
              this.model.formulaModifyFilesList.forEach((element) => {
                element.id = null
              })
            }

            console.log(this.model)
            httpAction(httpurl, this.model, method)
              .then((res) => {
                if (res.success) {
                  if (!this.model.id) {
                    this.model.dataId = res.message
                    that.applySubmit(this.model)
                  }
                  that.$message.success('保存成功')
                  that.$emit('ok')
                  that.close()
                } else {
                  that.$message.warning(res.message)
                }
              })
              .finally(() => {
                that.confirmLoading = false
              })
          }
        })
      },
      applySubmit(record) {
        if (record.dataId && record.dataId.length < 1) {
          this.$message.error('审批时必须传入参数dataId')
          return
        }

        isFirstInitiator(record.dataId, record).then((res) => {
          if (res.success && res.result) {
            // 只有第一次能自动申请
            return
          } else {
            var params = Object.assign(
              {
                dataId: record.dataId,
              },
              record
            )
            definitionStartByDataId(record.dataId, 'pgOrderFormulaModifyService', params)
              .then((res) => {
                if (res.success) {
                  this.$message.success(res.message)

                } else {
                  this.$message.error(res.message)
                }
              })
              .finally()
          }
        })
      },
      // handleDelDetail(props) {
      //   props.target.removeRows(props.row)
      //   this.ipsTslFormulaNoticeDetailTable.dataSource.splice(
      //     this.ipsTslFormulaNoticeDetailTable.dataSource.findIndex((d) => d.id === props.row.id),
      //     1
      //   )
      // },
      handleOk() {
        //空方法 防止多次提交
      },
      popupCallback(value,row){
        this.model = Object.assign(this.model, row);
      },
      // 加载配方通知单详情
      async loadFormulaDetail(id) {
        try {
          console.log("formulaId :"+id)
          this.model.formulaId = id
          const res = await getAction(this.url.queryFormulaDetails, { id: id })
          if (res.success && res.result) {
            const main = res.result.main
            //主
            this.model = Object.assign({}, this.model, {
              formulaNumber: main.formulaNumber
            })

            const childList = res.result.childList
            this.formulaListTable = {
              ...this.formulaListTable,
              dataSource: childList.map(item => ({
                materialCode: item.materialCode,
                materialName: item.materialName,
                materialSpec: item.materialSpec,
                materialUnit_dictText: item.materialUnit_dictText,
                formulaProportion: item.formulaProportion,
                actualNumber: item.actualNumber,
              }))
            }

          } else {
            this.$message.warning(res.message || '配方清单明细加载失败')
          }
        } catch (e) {
          console.error('配方清单明细加载失败', e)
          this.$message.error('配方清单明细加载失败')
        }
      },
      handleValueChange({ row, column }) {
        const field = column.property;
        if (field === 'formulaProportion') {
          let proportion = parseFloat(row.formulaProportion) || 0;
          const fixed = (num) => Number((num).toFixed(4));
          row.weight1000Kg  = fixed(proportion / 100 * 1000);
          row.weight3500Kg  = fixed(proportion / 100 * 3500);
          row.weight4000Kg  = fixed(proportion / 100 * 4000);
          row.weight5000Kg  = fixed(proportion / 100 * 5000);
        }
      },
      formulaListFooter() {
        return (
          <div style="width: 100%; display: flex; gap: 8px; flex-wrap: nowrap; overflow-x: auto;">
          <div style="order: 1; flex: 0 1 auto; min-width: 15%; text-align: center; border-right: 1px solid #f0f0f0;">合计</div>
          <div style="order: 2; flex: 0 1 auto; min-width: 62.7%; text-align: right; border-right: 1px solid #f0f0f0;">{this.totalFormulaProportion}</div>
          <div style="order: 3; flex: 0 1 auto; min-width: 15.2%; text-align: right;">{this.totalActualNumber}</div>
          </div>
      );
      },
      handlePreviewFile(row) {
        console.log(row);
        let filePath = row.row.filePath
        FilePreview(filePath);
      },
    },
  }
</script>

<style scoped>
  .ant-form-item {
    margin-bottom: 4px;
    margin-left: 4px;
  }
</style>
